<template>
  <div class="shoppingCart">
    <h1 v-if="success">{{ msg }}</h1>
    <table>
      <caption>
        商品结算
      </caption>
      <tr>
        <th></th>
        <th>商品名称</th>
        <th>单价</th>
        <th>数量</th>
        <th>金额</th>
      </tr>
      <tr v-for="book in books" :key="book.id">
        <td><img :src="book.imgUrl" /></td>
        <td>
          <router-link
            :to="{ name: 'book', params: { id: book.id } }"
            target="_blank"
          >
            {{ book.title }}
          </router-link>
        </td>
        <td>{{ currency(book.price) }}</td>
        <td>
          {{ book.quantity }}
        </td>
        <td>{{ currency(cartItemPrice(book.id)) }}</td>
      </tr>
    </table>
    <p>
      <span><button class="pay" @click="pay">付款</button></span>
      <span>总价：{{ currency(cartTotalPrice) }}</span>
    </p>
  </div>
</template>

<script setup lang="ts">
import { useCartStore } from '@/stores'
import { computed, ref, inject } from 'vue'
const store = useCartStore()
const success = ref(false)
const msg = ref('付款成功！')
const books = computed(() => store.items)
const cartItemPrice = computed(() => store.cartItemPrice)
const cartTotalPrice = computed(() => store.cartTotalPrice)
// const itemPrice = (price: number, count: number) => price * count
const setCartItems = (items) => store.setCartItems(items)
const currency = inject('currency')
function pay() {
  setCartItems({ items: [] })
  success.value = true
}
</script>

<style scoped>
.shoppingCart {
  text-align: center;
  margin-left: 45px;
  width: 96%;
  margin-top: 70px;
}
.shoppingCart h1 {
  color: red;
}
.shoppingCart table {
  border: solid 1px black;
  width: 100%;
  background-color: #eee;
}

.shoppingCart table > caption {
  font-size: 1.5em;
  font-weight: bold;
  margin: 5px 0 8px 0;
}

.shoppingCart th {
  height: 50px;
}
.shoppingCart th,
.shoppingCart td {
  border-bottom: solid 1px #ddd;
  text-align: center;
}
.shoppingCart span {
  float: right;
  padding-right: 15px;
}

.shoppingCart img {
  width: 60px;
  height: 60px;
}
.shoppingCart .pay {
  float: right;
  width: 60px;
  height: 30px;
  margin: 0;
  border: none;
  color: white;
  background-color: red;
  cursor: pointer;
}
</style>
